<template>
	<view class="local-water">
		<gyd-navbar back-color="#fff" :title="title" :isBack="false"></gyd-navbar>

		<view class="local-content">
			<view class="deliver-type">
				<view class="item" :class="{active:params.delivery_current==index}"
					v-for="(item,index) in delivery_type" :key="index" @click="changeDeliveryType(index)">{{item}}
				</view>
			</view>

			<!--收货地址-->
			<view class="delivery-address" v-if="params.delivery_current==0">
				<view class="card address" v-if="address">
					<uni-icons type="location-filled" size="32" color="#125cd7"></uni-icons>
					<view class="info">
						<view class="user">
							<text class="name">{{address.consignee}}</text>
							{{address.mobile}}
						</view>
						<view class="area">
							{{address.format_address}}
						</view>
					</view>
					<view class="arrow" @click="pageRoute('/userPages/address/address?order=1')">切换<uni-icons
							type="right" size="24" color="#c2c2c2"></uni-icons></view>
				</view>

				<view class="card address" style="width:100%;" v-if="!address">
					<uni-icons type="location-filled" size="32" color="#ddd"></uni-icons>
					<view class="info" style="display: flex;justify-content: space-between;">
						<view class="user">
							<text class="name">请添加地址</text>
						</view>
						<view class="arrow" @click="pageRoute('/userPages/address/address?order=1')">添加<uni-icons
								type="right" size="24" color="#c2c2c2"></uni-icons></view>
					</view>
				</view>
			</view>

			<view class="delivery_time" v-if="params.delivery_current==0">
				<view class="content">预约配送时间
				</view>
				<view class="times">{{delivery_time}}</view>
				<view class="arrow">
					<uni-datetime-picker type="datetime" v-model="delivery_time" :start="startTime" :end="endTime"
						:hide-second="true" @change="changeDeliveryTime">
						<uni-icons type="right" size="24" color="#c2c2c2"></uni-icons>
					</uni-datetime-picker>
				</view>
			</view>

			<!--自提点-->
			<view class="delivery-store" v-if="params.delivery_current==1">
				<view class="has-store" @click="pageRoute('/waterPages/store/store-list')" v-if="storeInfo">
					<view class="left-con">
						<view class="info">
							<view class="name">{{storeInfo.store_name}}</view>
							<view class="distance">距离:{{storeInfo.distance}}km</view>
						</view>
						<view class="address">{{storeInfo.store_address}}</view>
						<view class="times">营业时间：{{storeInfo.business_hours_start}} - {{storeInfo.business_hours_end}}
						</view>
					</view>
					<view class="arrow">切换<uni-icons type="right" size="24" color="#c2c2c2"></uni-icons></view>
				</view>
				<view class="no-store" @click="pageRoute('/waterPages/store/store-list')" v-if="!storeInfo">
					<view class="name">请选择自提点</view>
					<view><uni-icons type="right" size="24" color="#c2c2c2"></uni-icons></view>
				</view>
			</view>

			<view class="speak-water">
				<!--左侧侧边栏-->
				<view class="water-left">
					<view class="item" v-for="(item,index) in categoryList" :key="index"
						:class="{active:params.category_id == item.id}" @click="selectCategory(item)">
						<view class="name">{{item.name}}</view>
						<view class="desc">{{item.subtitle}}</view>
					</view>
				</view>

				<!--右侧内容-->
				<scroll-view class="water-right" scroll-y="true">
					<view>
						<view class="sort">
							<view class="item" :class="{active:params.is_free_queuing==0}" @click="changeBuyType(0)">
								正价购买
							</view>
							<view class="item" :class="{active:params.is_free_queuing==1}" @click="changeBuyType(1)">
								排队免单
							</view>
						</view>
						<view class="water-product-list">
							<water-goods :address="address" :isFreeQueuing="params.is_free_queuing" :goods="product"
								:deliveryCurrent="params.delivery_current" :deliveryTime="delivery_time"
								:storeInfo="storeInfo" v-for="(product, index) in productList"
								:key="index"></water-goods>
						</view>
						<view class="empty" v-if="productList.length <= 0" style="">
							<image :src="imgHost+ '/static/images/empty.png'" mode="aspectFill"></image>
							<text>暂无数据~</text>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import util from '@/utils/util';
	import {
		reactive,
		toRefs,
		inject,
		ref,
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';

	const state = reactive({
		title: '订水',
		themeColor: cache.get('themeColor'),
		imgHost: util.requestUrl(),


		delivery_type: ['配送', '自提'],
		address: null,
		address_id: 0,
		delivery_time: '',
		startTime: '2025-10-20 09:00:00',
		endTime: '2099-12-31 20:00:00',
		currentDate: '',
		storeInfo: null,

		categoryList: [],
		params: {
			keyword: '',
			delivery_current: 0,
			store_id: 0,
			category_id: 0,
			category_flag: 'all',
			is_free_queuing: 0,
			skip: 0,
		},
		isMore: true,
		productList: [],
	});

	//在页面所有元素加载完成后执行（只执行一次）
	onLoad((opt) => {
		console.log('onLoad');
		if (opt.hasOwnProperty('keyword')) {
			state.params.keyword = opt.keyword;
		}
		console.log('搜索关键字', state.params.keyword);
		if (opt.hasOwnProperty('is_free_queuing')) {
			state.params.is_free_queuing = parseInt(opt.is_free_queuing);
		}
		console.log('排队免单', state.params.is_free_queuing);
		initData();
	});

	//在页面由不可见变为可见时执行（只要页面显示都会执行）
	onShow(() => {
		console.log('onShow');
	})

	//在页面解析完成之后执行
	onReady(() => {
		console.log('onReady');
		getTimeRange();
	})

	onPullDownRefresh(() => {
		console.log('下拉刷新');
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
		state.params.keyword = '';
		state.isMore = true;
		state.productList = [];
		getProductList();
	})

	onReachBottom(() => {
		console.log('触底加载更多');
		getProductList();
	})

	function initData() {
		getLocation();
		getCategory();
		// getNearStore();

		getAddressInfo();
		getOrderInfo();
		getProductList();
	}

	function getLocation() {
		util.getLocation();
		setTimeout(() => {
			state.longitude = cache.get('longitude', false) || '';
			state.latitude = cache.get('latitude', false) || '';
		}, 1000);
	}

	function getCategory() {
		let params = {
			parent_id: 9,
		}
		request.get('goods/getProductCategory', params).then(res => {
			console.log('产品分类', res);
			state.categoryList = res.data.list;
			state.categoryList.unshift({
				id: 0,
				name: '全部商品',
				subtitle: '',
				flag: 'all'
			});
		})
	}

	function getNearStore() {
		state.storeInfo = {
			id: 1,
			store_name: '云海水站',
			distance: 3.26,
			store_address: '云南省昆明市五华区丰宁街道金鼎山路与长虹路交叉口东南150米',
			business_hours_start: '09:00',
			business_hours_end: '20:00'
		};
		state.params.store_id = 1;
	}

	function getProductList() {
		if (!state.isMore) {
			util.showTip('没有更多了');
			return;
		}
		state.params.skip = state.productList.length;
		request.get('goods/productList', state.params).then(res => {
			console.log('商品列表', res);
			state.isMore = res.data.is_more;
			if (state.productList.length == 0) {
				state.productList = res.data.list;
			} else {
				state.productList = state.productList.concat(res.data.list);
			}
		});
	}

	function getAddressInfo() {
		state.address = {
			id: 1,
			consignee: '王先生',
			mobile: '15825258992',
			format_address: '云南省昆明市五华区丰宁街道金鼎科技园18号平台A座101'
		};
		state.address_id = 1;

		/* if (state.params.delivery_current == 0) {
			state.isMore = true;
			state.productList = [];
			getProductList();
		} */
	}

	function getOrderInfo() {

	}

	function changeDeliveryTime(e) {
		console.log('选择预约配送时间', e);
		state.delivery_time = e;

		verifyDeliveryTime();
	}

	function changeDeliveryType(index) {
		console.log('切换配送类型', index);
		state.params.delivery_current = index;
		if (state.params.delivery_current) {
			getNearStore();
		}
		state.isMore = true;
		state.productList = [];
		setTimeout(() => {
			getProductList();
		}, 1000);
	}

	function selectCategory(item) {
		console.log('选择分类', item);
		state.params.category_id = item.id;
		state.params.category_flag = item.flag;
		state.isMore = true;
		state.productList = [];
		getProductList();
	}

	function changeBuyType(index) {
		console.log('切换购买方式', index);
		state.params.is_free_queuing = index;
		state.isMore = true;
		state.productList = [];
		getProductList();
	}

	function getTimeRange() {
		let date = new Date();
		let timestamp = date.getTime();
		state.currentDate = util.timestampToDate(timestamp, 'Y-m-d');
		let oneHour = 1 * 60 * 60 * 1000; // 一小时的毫秒数
		state.startTime = util.timestampToDate(timestamp + oneHour); // 加上一小时的时间
		let threeDays = 4 * 24 * 60 * 60 * 1000; // 四天的毫秒数
		state.endTime = util.timestampToDate(timestamp + threeDays); // 加上四天的时间
		console.log('预约时间范围', state.startTime, state.endTime);
	}

	function verifyDeliveryTime() {
		let current_time = new Date().getTime();
		let oneHour = 1 * 60 * 60 * 1000; // 一小时的毫秒数
		const delivery_time = util.formatToTimestamp(state.delivery_time);
		const business_start = util.formatToTimestamp(state.currentDate + ' ' + state.storeInfo.business_hours_start);
		const business_end = util.formatToTimestamp(state.currentDate + ' ' + state.storeInfo.business_hours_end);
		console.log(current_time, delivery_time, business_start, business_end);
		if (delivery_time < current_time + oneHour) {
			util.showTip('最早只能预约一小时后配送');
			return;
		}
		if (delivery_time < business_start || delivery_time > business_end) {
			util.showTip('不在配送时间内');
			return;
		}
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	}

	function pageTabRoute(url) {
		uni.reLaunch({
			url
		});
	}

	const {
		title,
		themeColor,
		imgHost,
		delivery_type,
		address,
		address_id,
		delivery_time,
		startTime,
		endTime,
		currentDate,
		storeInfo,
		categoryList,
		params,
		isMore,
		productList,
	} = toRefs(state);
</script>

<style lang="scss">
	.local-water {
		position: relative;
		height: 100vh;

		.local-content {

			// 配送类型
			.deliver-type {
				display: flex;
				justify-content: space-around;
				margin: $m24 0 $m24 0;

				.item {
					flex: 1;
					display: inline-block;
					margin: 0 20rpx;
					padding: 6px 0;
					text-align: center;
					background: #fff;
					border-radius: 10rpx;
					font-size: 28rpx;

					&.active {
						background: #125cd7;
						color: #fff;
					}
				}
			}

			// 配送地址
			.delivery-address {
				display: flex;
				align-items: center;
				padding: $m16 $m16;
				margin: $m24 $m24 0 $m24;
				background-color: $u-bg-reverse-color;
				border-radius: $radius-12;

				.card {
					border-radius: $radius-12;
					display: block;

					&.address {
						@include f-between;

						.info {
							flex: 1;
							margin-left: $m24;
							align-items: center;

							.user {
								color: $u-tips-color;

								.name {
									margin-right: $m24;
									font-size: $font-30;
									color: $u-main-color;
									font-weight: 500;
								}
							}

							.area {
								color: $u-tips-color;
							}
						}

						.arrow {
							// width: 120rpx;
							text-align: right;
							display: flex;
							align-items: center;
						}
					}
				}
			}

			.delivery_time {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: $m16 $m16;
				margin: $m24 $m24 0 $m24;
				background-color: $u-bg-reverse-color;
				border-radius: $radius-12;

				.content {
					margin-right: 30rpx;
				}

				.times {
					flex: 1;
				}

				.arrow {}
			}

			// 自提点
			.delivery-store {
				padding: $m16;
				margin: $m16 $m24 0 $m24;
				background-color: $u-bg-reverse-color;
				border-radius: $radius-12;

				.has-store {
					display: flex;
					align-items: center;

					.left-con {
						flex: 1;

						.info {
							display: flex;
							justify-content: flex-start;
							align-items: center;
							margin-bottom: 6rpx;

							.name {
								font-size: 30rpx;
								color: #313131;
								font-weight: 600;
							}

							.distance {
								margin-left: 10rpx;
								font-size: 24rpx;
								color: #125cd7;
							}
						}

						.address,
						.times {
							font-size: 28rpx;
						}
					}

					.arrow {
						// width: 130rpx;
						text-align: right;
						display: flex;
						align-items: center;
					}
				}

				.no-store {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.name {
						margin-right: $m24;
						font-size: $font-30;
						color: $u-main-color;
						font-weight: 500;
					}
				}
			}


			.speak-water {
				display: flex;

				.water-left {
					width: 180rpx;
					margin-top: $m24;
					background: #fff;

					.item {
						height: 110rpx;
						padding: 22rpx 0 0 20rpx;
						line-height: 30px;
						text-align: left;

						.name {}

						.desc {
							font-size: 22rpx;
						}

						&.active {
							background: #d3dff7;
							border-left: #125cd7 solid 4rpx;

							view {
								color: #125cd7;
								font-weight: 600;
							}
						}
					}
				}

				.water-right {
					flex: 1;
					height: 89vh;
					padding-bottom: 110rpx;

					//排序
					.sort {
						display: flex;
						justify-content: flex-start;
						padding: $m24 0 0 $m24;

						.item {
							background: #fff;
							padding: 4rpx 12rpx;
							border-radius: 6rpx;
							margin: 0 $m24 0 0;
							font-size: 24rpx;

							&.active {
								background: #125cd7;
								color: #fff;
							}
						}
					}


					.water-product-list {
						width: 100%;
						padding: 9px 11px 0;
					}

					.empty {
						text-align: center;
						margin-top: 30rpx;

						image {
							display: block;
							width: 300rpx;
							height: 300rpx;
							margin: 0 auto;
						}
					}
				}
			}
		}
	}
</style>